package com.jt.www.util;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import sun.misc.BASE64Encoder;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.PBEParameterSpec;
import java.security.MessageDigest;

/**
 * @author xq.wu03
 * @Classname SecurityUrl
 * @Description 诚泰电子保单加密
 * @create 2020-10-23 16:10
 */
public class SecurityUrl {

    protected final static Log logger = LogFactory.getLog(SecurityUrl.class);
    private final static int ITERATIONS = 20;

    public static String encrypt(String key, String plainText) throws Exception {
        try {
            byte[] salt = new byte[8];
            MessageDigest md = MessageDigest.getInstance("MD5");
            md.update(key.getBytes());
            byte[] digest = md.digest();
            for (int i = 0; i < 8; i++) {
                salt[i] = digest[i];
            }
            PBEKeySpec pbeKeySpec = new PBEKeySpec(key.toCharArray());
            SecretKeyFactory keyFactory = SecretKeyFactory
                    .getInstance("PBEWithMD5AndDES");
            SecretKey skey = keyFactory.generateSecret(pbeKeySpec);
            PBEParameterSpec paramSpec = new PBEParameterSpec(salt, ITERATIONS);
            Cipher cipher = Cipher.getInstance("PBEWithMD5AndDES");
            cipher.init(Cipher.ENCRYPT_MODE, skey, paramSpec);
            byte[] cipherText = cipher.doFinal(plainText.getBytes());
            String saltString = new String(Base64.encode(salt));
            String ciphertextString = new String(Base64.encode(cipherText));
            String re = saltString + ciphertextString;
            re = new BASE64Encoder().encode(re.getBytes());
            return re;
        } catch (Exception e) {
            throw new Exception("Encrypt Text Error:" + e.getMessage(), e);
        }
    }

    public static void main(String[] args) {
        String policyNO = "6010000120320200005545";
        String codeKey = "JTJJ";
        String padsas = "JTJJ";
        String ciphertext = "";
        try {
            ciphertext = SecurityUrl.encrypt(codeKey, policyNO);
            System.out.println("加密后参数：" + ciphertext);
            System.out.println("原参数：" + policyNO);
        } catch (Exception e) {
            e.printStackTrace();
            System.exit(-1);
        }
        System.out.println("http://183.224.42.121:9999/echannel/new/policy/download/partnerCode/" + padsas + "/policyNO/" + ciphertext);
    }
}
